package wang;

import com.rabbitmq.client.*;
import com.wang.Sys;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发布订阅模式（广播模式） 生产者
 */
public class Producer {


    public static void main(String[] args) throws IOException, TimeoutException {

        // 1.创建连接工厂
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost(Sys.HOST);
        cf.setPort(Sys.PORT);
        cf.setVirtualHost(Sys.VIRTUALHOST);
        cf.setUsername(Sys.USER_NAME);
        cf.setPassword(Sys.PASSWORD);

        // 2.创建连接
        Connection connection = cf.newConnection();

        // 3.创建通道
        Channel channel = connection.createChannel();

        // 4.创建队列
        channel.queueDeclare(Sys.QUEUE_NAME_1,true,false,false,null);
        channel.queueDeclare(Sys.QUEUE_NAME_2,true,false,false,null);

        // 5.创建交换机
        channel.exchangeDeclare(Sys.EXCHANGE_NAME_1, BuiltinExchangeType.FANOUT, true);

        // 6.绑定交换机  BuiltinExchangeType.FANOUT类型 routingKey为空字符串
        channel.queueBind(Sys.QUEUE_NAME_1,Sys.EXCHANGE_NAME_1,"",null);
        channel.queueBind(Sys.QUEUE_NAME_2,Sys.EXCHANGE_NAME_1,"",null);

        // 7.发送消息
        for (int i = 0; i<20; i++) {
            String message = "publish-subscribe......" + i;
            channel.basicPublish(Sys.EXCHANGE_NAME_1, "",null, message.getBytes());
        }



    }

}
